This repository has been archived by the owner on May 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 448
/
Copy pathNewTabPageViewController.swift
1085 lines (948 loc) · 41.7 KB
/
NewTabPageViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 The Brave Authors. All rights reserved.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import UIKit
import BraveUI
import CoreData
import Data
import Shared
import BraveShared
import BraveCore
import SnapKit
import SwiftUI
import BraveNews
import Combine
import DesignSystem
import Growth
/// The behavior for sizing sections when the user is in landscape orientation
enum NTPLandscapeSizingBehavior {
/// The section is given half the available space
///
/// Layout is decided by device type (iPad vs iPhone)
case halfWidth
/// The section is given the full available space
///
/// Layout is up to the section to define
case fullWidth
}
/// A section that will be shown in the NTP. Sections are responsible for the
/// layout and interaction of their own items
protocol NTPSectionProvider: NSObject, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
/// Register cells and supplimentary views for your section to
/// `collectionView`
func registerCells(to collectionView: UICollectionView)
/// The defined behavior when the user is in landscape.
///
/// Defaults to `halfWidth`, which will only give half of the available
/// width to the section (and adjust layout automatically based on device)
var landscapeBehavior: NTPLandscapeSizingBehavior { get }
}
extension NTPSectionProvider {
var landscapeBehavior: NTPLandscapeSizingBehavior { .halfWidth }
/// The bounding size for auto-sizing cells, bound to the maximum available
/// width in the collection view, taking into account safe area insets and
/// insets for that given section
func fittingSizeForCollectionView(_ collectionView: UICollectionView, section: Int) -> CGSize {
let sectionInset: UIEdgeInsets
if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
if let flowLayoutDelegate = collectionView.delegate as? UICollectionViewDelegateFlowLayout {
sectionInset = flowLayoutDelegate.collectionView?(collectionView, layout: collectionView.collectionViewLayout, insetForSectionAt: section) ?? flowLayout.sectionInset
} else {
sectionInset = flowLayout.sectionInset
}
} else {
sectionInset = .zero
}
return CGSize(
width: collectionView.bounds.width - collectionView.safeAreaInsets.left - collectionView.safeAreaInsets.right - sectionInset.left - sectionInset.right,
height: 1000
)
}
}
/// A section provider that can be observed for changes to tell the
/// `NewTabPageViewController` to reload its section
protocol NTPObservableSectionProvider: NTPSectionProvider {
var sectionDidChange: (() -> Void)? { get set }
}
protocol NewTabPageDelegate: AnyObject {
func focusURLBar()
func navigateToInput(_ input: String, inNewTab: Bool, switchingToPrivateMode: Bool)
func handleFavoriteAction(favorite: Favorite, action: BookmarksAction)
func brandedImageCalloutActioned(_ state: BrandedImageCalloutState)
func tappedQRCodeButton(url: URL)
func showNTPOnboarding()
}
/// The new tab page. Shows users a variety of information, including stats and
/// favourites
class NewTabPageViewController: UIViewController {
weak var delegate: NewTabPageDelegate?
var ntpStatsOnboardingFrame: CGRect? {
guard let section = sections.firstIndex(where: { $0 is StatsSectionProvider }) else {
return nil
}
if let cell = collectionView.cellForItem(at: IndexPath(item: 0, section: section)) as? NewTabCenteredCollectionViewCell<BraveShieldStatsView> {
return cell.contentView.convert(cell.contentView.frame, to: view)
}
return nil
}
/// The modules to show on the new tab page
private var sections: [NTPSectionProvider] = []
private let layout = NewTabPageFlowLayout()
private let collectionView: NewTabCollectionView
private weak var tab: Tab?
private let rewards: BraveRewards
private var background: NewTabPageBackground
private let backgroundView = NewTabPageBackgroundView()
private let backgroundButtonsView = NewTabPageBackgroundButtonsView()
/// A gradient to display over background images to ensure visibility of
/// the NTP contents and sponsored logo
///
/// Only should be displayed when the user has background images enabled
let gradientView = GradientView(
colors: [
UIColor(white: 0.0, alpha: 0.5),
UIColor(white: 0.0, alpha: 0.0),
UIColor(white: 0.0, alpha: 0.3),
],
positions: [0, 0.5, 0.8],
startPoint: .zero,
endPoint: CGPoint(x: 0, y: 1)
)
private let feedDataSource: FeedDataSource
private let feedOverlayView = NewTabPageFeedOverlayView()
private var preventReloadOnBraveNewsEnabledChange = false
private let notifications: NewTabPageNotifications
private var cancellables: Set<AnyCancellable> = []
init(
tab: Tab,
profile: Profile,
dataSource: NTPDataSource,
feedDataSource: FeedDataSource,
rewards: BraveRewards
) {
self.tab = tab
self.rewards = rewards
self.feedDataSource = feedDataSource
background = NewTabPageBackground(dataSource: dataSource)
notifications = NewTabPageNotifications(rewards: rewards)
collectionView = NewTabCollectionView(frame: .zero, collectionViewLayout: layout)
super.init(nibName: nil, bundle: nil)
Preferences.NewTabPage.showNewTabPrivacyHub.observe(from: self)
Preferences.NewTabPage.showNewTabFavourites.observe(from: self)
sections = [
StatsSectionProvider(openPrivacyHubPressed: { [weak self] in
if PrivateBrowsingManager.shared.isPrivateBrowsing {
return
}
let host = UIHostingController(rootView: PrivacyReportsManager.prepareView())
host.rootView.onDismiss = { [weak self, weak host] in
host?.dismiss(animated: true) {
guard let self = self else { return }
// Handle App Rating
// User finished viewing the privacy report (tapped close)
AppReviewManager.shared.handleAppReview(for: self)
}
}
host.rootView.openPrivacyReportsUrl = { [weak self] in
self?.delegate?.navigateToInput(
BraveUX.privacyReportsURL.absoluteString,
inNewTab: false,
// Privacy Reports view is unavailable in private mode.
switchingToPrivateMode: false
)
}
self?.present(host, animated: true)
}, hidePrivacyHubPressed: { [weak self] in
Preferences.NewTabPage.showNewTabPrivacyHub.value = false
self?.collectionView.reloadData()
}),
FavoritesSectionProvider(action: { [weak self] bookmark, action in
self?.handleFavoriteAction(favorite: bookmark, action: action)
}, legacyLongPressAction: { [weak self] alertController in
self?.present(alertController, animated: true)
}),
FavoritesOverflowSectionProvider(action: { [weak self] in
self?.delegate?.focusURLBar()
}),
]
// This is a one-off view, adding it to the NTP only if necessary.
if NTPDefaultBrowserCalloutProvider.shouldShowCallout {
sections.insert(NTPDefaultBrowserCalloutProvider(), at: 0)
}
if !PrivateBrowsingManager.shared.isPrivateBrowsing {
sections.append(
BraveNewsSectionProvider(
dataSource: feedDataSource,
rewards: rewards,
actionHandler: { [weak self] in
self?.handleBraveNewsAction($0)
}
)
)
layout.braveNewsSection = sections.firstIndex(where: { $0 is BraveNewsSectionProvider })
}
collectionView.do {
$0.delegate = self
$0.dataSource = self
$0.dragDelegate = self
$0.dropDelegate = self
}
background.changed = { [weak self] in
self?.setupBackgroundImage()
}
Preferences.BraveNews.isEnabled.observe(from: self)
feedDataSource.$state
.scan((.initial, .initial), { ($0.1, $1) })
.receive(on: DispatchQueue.main)
.sink { [weak self] (oldState, newState) in
self?.handleFeedStateChange(oldState, newState)
}
.store(in: &cancellables)
NotificationCenter.default.addObserver(self, selector: #selector(checkForUpdatedFeed), name: UIApplication.didBecomeActiveNotification, object: nil)
}
@available(*, unavailable)
required init(coder: NSCoder) {
fatalError()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(backgroundView)
view.insertSubview(gradientView, aboveSubview: backgroundView)
view.addSubview(collectionView)
view.addSubview(feedOverlayView)
collectionView.backgroundView = backgroundButtonsView
feedOverlayView.headerView.settingsButton.addTarget(self, action: #selector(tappedBraveNewsSettings), for: .touchUpInside)
if !AppConstants.buildChannel.isPublic {
feedOverlayView.headerView.settingsButton.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(longPressedBraveNewsSettingsButton)))
}
feedOverlayView.newContentAvailableButton.addTarget(self, action: #selector(tappedNewContentAvailable), for: .touchUpInside)
backgroundButtonsView.tappedActiveButton = { [weak self] sender in
self?.tappedActiveBackgroundButton(sender)
}
setupBackgroundImage()
backgroundView.snp.makeConstraints {
$0.edges.equalToSuperview()
}
collectionView.snp.makeConstraints {
$0.edges.equalToSuperview()
}
feedOverlayView.snp.makeConstraints {
$0.edges.equalToSuperview()
}
gradientView.snp.makeConstraints {
$0.edges.equalTo(backgroundView)
}
sections.enumerated().forEach { (index, provider) in
provider.registerCells(to: collectionView)
if let observableProvider = provider as? NTPObservableSectionProvider {
observableProvider.sectionDidChange = { [weak self] in
UIView.performWithoutAnimation {
self?.collectionView.reloadSections(IndexSet(integer: index))
}
}
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
checkForUpdatedFeed()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.reloadData()
// Make sure that imageView has a frame calculated before we attempt
// to use it.
backgroundView.layoutIfNeeded()
calculateBackgroundCenterPoints()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
reportSponsoredImageBackgroundEvent(.viewed)
presentNotification()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.50) {
self.delegate?.showNTPOnboarding()
}
}
override func viewSafeAreaInsetsDidChange() {
super.viewSafeAreaInsetsDidChange()
backgroundButtonsView.collectionViewSafeAreaInsets = view.safeAreaInsets
}
override func willMove(toParent parent: UIViewController?) {
super.willMove(toParent: parent)
backgroundView.imageView.image = parent == nil ? nil : background.backgroundImage
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
if previousTraitCollection?.verticalSizeClass
!= traitCollection.verticalSizeClass {
calculateBackgroundCenterPoints()
}
}
// MARK: - Background
/// Hide any visible sponsored image notification if the current background
/// is no longer a sponsored image. If the visible notification is not
/// for sponsored images, this does nothing.
private func hideVisibleSponsoredImageNotification() {
if case .brandedImages = visibleNotification {
guard let background = background.currentBackground else {
hideNotification()
return
}
switch background.type {
case .regular, .withQRCode:
hideNotification()
case .withBrandLogo:
// Current background is still a sponsored image so it can stay
// visible
break
}
}
}
func setupBackgroundImage() {
collectionView.reloadData()
hideVisibleSponsoredImageNotification()
if let backgroundType = background.currentBackground?.type {
switch backgroundType {
case .regular:
if let name = background.currentBackground?.wallpaper.credit?.name {
backgroundButtonsView.activeButton = .imageCredit(name)
} else {
backgroundButtonsView.activeButton = .none
}
case .withBrandLogo(let defaultLogo):
guard let logo = background.currentBackground?.wallpaper.logo ?? defaultLogo else { break }
backgroundButtonsView.activeButton = .brandLogo(logo)
case .withQRCode(_):
backgroundButtonsView.activeButton = .QRCode
}
} else {
backgroundButtonsView.activeButton = .none
}
gradientView.isHidden = background.backgroundImage == nil
backgroundView.imageView.image = background.backgroundImage
}
private func calculateBackgroundCenterPoints() {
// Only iPhone portrait looking devices have their center of the image offset adjusted.
// In other cases the image is always centered.
guard let image = backgroundView.imageView.image,
traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .regular else {
// Reset the previously calculated offset.
backgroundView.updateImageXOffset(by: 0)
return
}
// If no focal point provided we do nothing. The image is centered by default.
guard let focalX = background.currentBackground?.wallpaper.focalPoint?.x else {
return
}
// Calculate the sizing difference between `image` and `imageView` to determine the pixel difference ratio.
// Most image calculations have to use this property to get coordinates right.
let sizeRatio = backgroundView.imageView.frame.size.height / image.size.height
// How much the image should be offset according to the set focal point coordinate.
// We calculate it by looking how much to move the image away from the center of the image.
let focalXOffset = ((image.size.width / 2) - focalX) * sizeRatio
// Amount of image space which is cropped on one side, not visible on the screen.
// We use this info to prevent going of out image bounds when updating the `x` offset.
let extraHorizontalSpaceOnOneSide = ((image.size.width * sizeRatio) - backgroundView.frame.width) / 2
// The offset proposed by the focal point might be too far away from image's center
// resulting in not having anough image space to cover entire width of the view and leaving blank space.
// If the focal offset goes out of bounds we center it to the maximum amount we can where the entire
// image is able to cover the view.
let realisticXOffset = abs(focalXOffset) > extraHorizontalSpaceOnOneSide ?
extraHorizontalSpaceOnOneSide : focalXOffset
backgroundView.updateImageXOffset(by: realisticXOffset)
}
private func reportSponsoredImageBackgroundEvent(_ event: Ads.NewTabPageAdEventType) {
guard let backgroundType = background.currentBackground?.type,
case .withBrandLogo = backgroundType,
let creativeInstanceId = background.currentBackground?.wallpaper.creativeInstanceId
else {
return
}
rewards.ads.reportNewTabPageAdEvent(
background.wallpaperId.uuidString,
creativeInstanceId: creativeInstanceId,
eventType: event
)
}
// MARK: - Notifications
private var notificationController: UIViewController?
private var visibleNotification: NewTabPageNotifications.NotificationType?
private var notificationShowing: Bool {
notificationController?.parent != nil
}
private func presentNotification() {
if PrivateBrowsingManager.shared.isPrivateBrowsing || notificationShowing {
return
}
var isShowingSponseredImage = false
if case .withBrandLogo(let logo) = background.currentBackground?.type, logo != nil {
isShowingSponseredImage = true
}
guard
let notification = notifications.notificationToShow(
isShowingBackgroundImage: background.currentBackground != nil,
isShowingSponseredImage: isShowingSponseredImage
)
else {
return
}
var vc: UIViewController?
switch notification {
case .brandedImages(let state):
if Preferences.NewTabPage.atleastOneNTPNotificationWasShowed.value { return }
guard let notificationVC = NTPNotificationViewController(state: state, rewards: rewards) else { return }
notificationVC.closeHandler = { [weak self] in
self?.notificationController = nil
}
notificationVC.learnMoreHandler = { [weak self] in
self?.delegate?.brandedImageCalloutActioned(state)
}
vc = notificationVC
}
guard let viewController = vc else { return }
notificationController = viewController
visibleNotification = notification
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak self] in
guard let self = self else { return }
if case .brandedImages = notification {
Preferences.NewTabPage.atleastOneNTPNotificationWasShowed.value = true
}
self.addChild(viewController)
self.view.addSubview(viewController.view)
}
}
private func hideNotification() {
guard let controller = notificationController else { return }
controller.willMove(toParent: nil)
controller.removeFromParent()
controller.view.removeFromSuperview()
notificationController = nil
}
// MARK: - Brave News
private func handleBraveNewsAction(_ action: BraveNewsSectionProvider.Action) {
switch action {
case .optInCardAction(.closedButtonTapped):
Preferences.BraveNews.isShowingOptIn.value = false
if let section = layout.braveNewsSection, collectionView.numberOfItems(inSection: section) != 0 {
collectionView.deleteItems(at: [IndexPath(item: 0, section: section)])
}
// We check if first item exists before scrolling up to it.
// This should never happen since first item is our shields stats view.
// However we saw it crashing in XCode logs, see #4202.
let firstItemIndexPath = IndexPath(item: 0, section: 0)
if let itemCount = collectionView.dataSource?.collectionView(collectionView, numberOfItemsInSection: 0),
itemCount > 0, // Only scroll if the section has items, otherwise it will crash.
collectionView.dataSource?
.collectionView(collectionView, cellForItemAt: firstItemIndexPath) != nil {
collectionView.scrollToItem(at: firstItemIndexPath, at: .top, animated: true)
} else {
// Cannot scorll to deleted item index.
// Collection-View datasource never changes or updates
// Therefore we need to scroll to offset 0.
// See: #4575.
collectionView.setContentOffset(.zero, animated: true)
}
collectionView.verticalScrollIndicatorInsets = .zero
UIView.animate(withDuration: 0.25) {
self.feedOverlayView.headerView.alpha = 0.0
self.backgroundButtonsView.alpha = 1.0
}
case .optInCardAction(.learnMoreButtonTapped):
delegate?.navigateToInput(BraveUX.braveNewsPrivacyURL.absoluteString, inNewTab: false, switchingToPrivateMode: false)
case .optInCardAction(.turnOnBraveNewsButtonTapped):
preventReloadOnBraveNewsEnabledChange = true
Preferences.BraveNews.userOptedIn.value = true
Preferences.BraveNews.isShowingOptIn.value = false
Preferences.BraveNews.isEnabled.value = true
rewards.ads.initialize { [weak self] _ in
// Initialize ads if it hasn't already been done
self?.loadFeedContents()
}
case .emptyCardTappedSourcesAndSettings:
tappedBraveNewsSettings()
case .errorCardTappedRefresh:
loadFeedContents()
case .moreBraveOffersTapped:
delegate?.navigateToInput(
BraveUX.braveOffersURL.absoluteString,
inNewTab: false,
switchingToPrivateMode: false
)
case .bravePartnerLearnMoreTapped:
delegate?.navigateToInput(
BraveUX.braveNewsPartnersURL.absoluteString,
inNewTab: false,
switchingToPrivateMode: false
)
case .itemAction(.opened(let inNewTab, let switchingToPrivateMode), let context):
guard let url = context.item.content.url else { return }
let item = context.item
if !switchingToPrivateMode, item.content.contentType == .partner,
let creativeInstanceID = item.content.creativeInstanceID {
rewards.ads.reportPromotedContentAdEvent(
item.content.urlHash,
creativeInstanceId: creativeInstanceID,
eventType: .clicked
)
}
delegate?.navigateToInput(
url.absoluteString,
inNewTab: inNewTab,
switchingToPrivateMode: switchingToPrivateMode
)
/// Donate Open Brave News Activity for Custom Suggestions
let openBraveNewsActivity = ActivityShortcutManager.shared.createShortcutActivity(type: .openBraveNews)
self.userActivity = openBraveNewsActivity
openBraveNewsActivity.becomeCurrent()
case .itemAction(.toggledSource, let context):
let isEnabled = feedDataSource.isSourceEnabled(context.item.source)
feedDataSource.toggleSource(context.item.source, enabled: !isEnabled)
if isEnabled {
let alert = FeedActionAlertView.feedDisabledAlertView(for: context.item)
alert.present(on: self)
}
case .inlineContentAdAction(.opened(let inNewTab, let switchingToPrivateMode), let ad):
guard let url = ad.targetURL.asURL else { return }
if !switchingToPrivateMode {
rewards.ads.reportInlineContentAdEvent(
ad.placementID,
creativeInstanceId: ad.creativeInstanceID,
eventType: .clicked
)
}
delegate?.navigateToInput(
url.absoluteString,
inNewTab: inNewTab,
switchingToPrivateMode: switchingToPrivateMode
)
case .inlineContentAdAction(.toggledSource, _):
// Inline content ads have no source
break
}
}
private var newContentAvailableDismissTimer: Timer? {
didSet {
oldValue?.invalidate()
}
}
private func handleFeedStateChange(
_ oldValue: FeedDataSource.State,
_ newValue: FeedDataSource.State
) {
guard let section = layout.braveNewsSection else { return }
func _completeLoading() {
UIView.animate(
withDuration: 0.2,
animations: {
self.feedOverlayView.loaderView.alpha = 0.0
},
completion: { _ in
self.feedOverlayView.loaderView.stop()
self.feedOverlayView.loaderView.alpha = 1.0
self.feedOverlayView.loaderView.isHidden = true
})
if collectionView.contentOffset.y == collectionView.contentInset.top {
collectionView.reloadData()
collectionView.layoutIfNeeded()
let cells = collectionView.indexPathsForVisibleItems
.filter { $0.section == section }
.compactMap(collectionView.cellForItem(at:))
cells.forEach { cell in
cell.transform = .init(translationX: 0, y: 200)
UIView.animate(
withDuration: 0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0, options: [.beginFromCurrentState],
animations: {
cell.transform = .identity
}, completion: nil)
}
} else {
collectionView.reloadSections(IndexSet(integer: section))
}
}
switch (oldValue, newValue) {
case (.loading, .loading):
// Nothing to do
break
case (
.failure(let error1 as NSError),
.failure(let error2 as NSError)
) where error1 == error2:
// Nothing to do
break
case (
.loading(.failure(let error1 as NSError)),
.failure(let error2 as NSError)
) where error1 == error2:
if let cell = collectionView.cellForItem(at: IndexPath(item: 0, section: section)) as? FeedCardCell<BraveNewsErrorView> {
cell.content.refreshButton.isLoading = false
} else {
_completeLoading()
}
case (_, .loading):
if collectionView.contentOffset.y == collectionView.contentInset.top || collectionView.numberOfItems(inSection: section) == 0 {
feedOverlayView.loaderView.isHidden = false
feedOverlayView.loaderView.start()
if let section = layout.braveNewsSection {
let numberOfItems = collectionView.numberOfItems(inSection: section)
if numberOfItems > 0 {
collectionView.deleteItems(
at: (0..<numberOfItems).map({ IndexPath(item: $0, section: section) })
)
}
}
}
case (.loading, _):
_completeLoading()
default:
collectionView.reloadSections(IndexSet(integer: section))
}
}
@objc private func checkForUpdatedFeed() {
if !isBraveNewsVisible || Preferences.BraveNews.isShowingOptIn.value { return }
if collectionView.contentOffset.y == collectionView.contentInset.top {
// Reload contents if the user is not currently scrolled into the feed
loadFeedContents()
} else {
if case .failure = feedDataSource.state {
// Refresh button already exists on the users failure card
return
}
// Possibly show the "new content available" button
if feedDataSource.shouldLoadContent {
feedOverlayView.showNewContentAvailableButton()
}
}
}
private func loadFeedContents(completion: (() -> Void)? = nil) {
if !feedDataSource.shouldLoadContent {
return
}
rewards.ads.purgeOrphanedAdEvents(.inlineContentAd) { _ in }
feedDataSource.load(completion)
}
// MARK: - Actions
@objc private func tappedNewContentAvailable() {
if case .loading = feedDataSource.state {
return
}
let todayStart = collectionView.frame.height - feedOverlayView.headerView.bounds.height - 32 - 16
newContentAvailableDismissTimer = nil
feedOverlayView.newContentAvailableButton.isLoading = true
loadFeedContents { [weak self] in
guard let self = self else { return }
self.feedOverlayView.hideNewContentAvailableButton()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.collectionView.setContentOffset(CGPoint(x: 0, y: todayStart), animated: true)
}
}
}
@objc private func tappedBraveNewsSettings() {
let controller = BraveNewsSettingsViewController(dataSource: feedDataSource, ads: rewards.ads)
controller.newsSettingsDidDismiss = {
AppReviewManager.shared.isReviewRequired = true
}
let container = UINavigationController(rootViewController: controller)
present(container, animated: true)
}
private func tappedActiveBackgroundButton(_ sender: UIControl) {
guard let background = background.currentBackground else { return }
switch background.type {
case .regular:
presentImageCredit(sender)
case .withBrandLogo(let defaultLogo):
guard let logo = background.wallpaper.logo ?? defaultLogo else { break }
tappedSponsorButton(logo)
case .withQRCode(let code):
tappedQRCode(code)
}
}
private func tappedSponsorButton(_ logo: NTPLogo) {
UIImpactFeedbackGenerator(style: .medium).bzzt()
delegate?.navigateToInput(logo.destinationUrl, inNewTab: false, switchingToPrivateMode: false)
reportSponsoredImageBackgroundEvent(.clicked)
}
private func tappedQRCode(_ code: String) {
// Super referrer websites come in format https://brave.com/r/REF_CODE
let refUrl = URL(string: "https://brave.com/")?
.appendingPathComponent("r")
.appendingPathComponent(code)
guard let url = refUrl else { return }
delegate?.tappedQRCodeButton(url: url)
}
private func handleFavoriteAction(favorite: Favorite, action: BookmarksAction) {
delegate?.handleFavoriteAction(favorite: favorite, action: action)
}
private func presentImageCredit(_ button: UIControl) {
guard let credit = background.currentBackground?.wallpaper.credit else { return }
let alert = UIAlertController(title: credit.name, message: nil, preferredStyle: .actionSheet)
if let creditWebsite = credit.url, let creditURL = URL(string: creditWebsite) {
let websiteTitle = String(format: Strings.viewOn, creditURL.hostSLD.capitalizeFirstLetter)
alert.addAction(
UIAlertAction(title: websiteTitle, style: .default) { [weak self] _ in
self?.delegate?.navigateToInput(creditWebsite, inNewTab: false, switchingToPrivateMode: false)
})
}
alert.popoverPresentationController?.sourceView = button
alert.popoverPresentationController?.permittedArrowDirections = [.down, .up]
alert.addAction(UIAlertAction(title: Strings.close, style: .cancel, handler: nil))
UIImpactFeedbackGenerator(style: .medium).bzzt()
present(alert, animated: true, completion: nil)
}
@objc private func longPressedBraveNewsSettingsButton() {
assert(
!AppConstants.buildChannel.isPublic,
"Debug settings are not accessible on public builds")
let settings = BraveNewsDebugSettingsView(dataSource: feedDataSource) { [weak self] in
self?.dismiss(animated: true)
}
let container = UINavigationController(
rootViewController: UIHostingController(rootView: settings)
)
present(container, animated: true)
}
}
extension NewTabPageViewController: PreferencesObserver {
func preferencesDidChange(for key: String) {
if key == Preferences.NewTabPage.showNewTabPrivacyHub.key || key == Preferences.NewTabPage.showNewTabFavourites.key {
collectionView.reloadData()
return
}
if !preventReloadOnBraveNewsEnabledChange {
collectionView.reloadData()
}
if !isBraveNewsVisible {
collectionView.verticalScrollIndicatorInsets = .zero
feedOverlayView.headerView.alpha = 0.0
backgroundButtonsView.alpha = 1.0
}
preventReloadOnBraveNewsEnabledChange = false
}
}
// MARK: - UIScrollViewDelegate
extension NewTabPageViewController {
var isBraveNewsVisible: Bool {
return !PrivateBrowsingManager.shared.isPrivateBrowsing && (Preferences.BraveNews.isEnabled.value || Preferences.BraveNews.isShowingOptIn.value)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
for section in sections {
section.scrollViewDidScroll?(scrollView)
}
guard isBraveNewsVisible, let newsSection = layout.braveNewsSection else { return }
if collectionView.numberOfItems(inSection: newsSection) > 0 {
// Hide the buttons as Brave News feeds appear
backgroundButtonsView.alpha = 1.0 - max(0.0, min(1.0, (scrollView.contentOffset.y - scrollView.contentInset.top) / 16))
// Show the header as Brave News feeds appear
// Offset of where Brave News starts
let todayStart = collectionView.frame.height - feedOverlayView.headerView.bounds.height - 32 - 16
// Offset of where the header should begin becoming visible
let alphaInStart = collectionView.frame.height / 2.0
let value = scrollView.contentOffset.y
let alpha = max(0.0, min(1.0, (value - alphaInStart) / (todayStart - alphaInStart)))
feedOverlayView.headerView.alpha = alpha
if feedOverlayView.newContentAvailableButton.alpha != 0 && !feedOverlayView.newContentAvailableButton.isLoading {
let velocity = scrollView.panGestureRecognizer.velocity(in: scrollView).y
if velocity > 0 && collectionView.contentOffset.y < todayStart {
// Scrolling up
self.feedOverlayView.hideNewContentAvailableButton()
} else if velocity < 0 {
// Scrolling down
if newContentAvailableDismissTimer == nil {
let timer = Timer(
timeInterval: 4,
repeats: false
) { [weak self] _ in
guard let self = self else { return }
self.feedOverlayView.hideNewContentAvailableButton()
self.newContentAvailableDismissTimer = nil
}
// Adding the timer manually under `common` mode allows it to execute while the user
// is scrolling through the feed rather than have to wait until input stops
RunLoop.main.add(timer, forMode: .common)
newContentAvailableDismissTimer = timer
}
}
}
}
}
/// Moves New Tab Page Scroll to start of Brave News - Used for shortcut
func scrollToBraveNews() {
// Offset of where Brave News starts
let todayStart = collectionView.frame.height - feedOverlayView.headerView.bounds.height - 32 - 16
collectionView.contentOffset.y = todayStart
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension NewTabPageViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
sections[indexPath.section].collectionView?(collectionView, didSelectItemAt: indexPath)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
sections[indexPath.section].collectionView?(collectionView, layout: collectionViewLayout, sizeForItemAt: indexPath) ?? .zero
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let sectionProvider = sections[section]
var inset = sectionProvider.collectionView?(collectionView, layout: collectionViewLayout, insetForSectionAt: section) ?? .zero
if sectionProvider.landscapeBehavior == .halfWidth {
let isIphone = UIDevice.isPhone
let isLandscape = view.frame.width > view.frame.height
if isLandscape {
let availableWidth = collectionView.bounds.width - collectionView.safeAreaInsets.left - collectionView.safeAreaInsets.right
if isIphone {
inset.left = availableWidth / 2.0
} else {
inset.right = availableWidth / 2.0
}
}
}
return inset
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
sections[section].collectionView?(collectionView, layout: collectionViewLayout, minimumLineSpacingForSectionAt: section) ?? 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
sections[section].collectionView?(collectionView, layout: collectionViewLayout, minimumInteritemSpacingForSectionAt: section) ?? 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
sections[section].collectionView?(collectionView, layout: collectionViewLayout, referenceSizeForHeaderInSection: section) ?? .zero
}
}
// MARK: - UICollectionViewDelegate
extension NewTabPageViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
sections[indexPath.section].collectionView?(collectionView, willDisplay: cell, forItemAt: indexPath)
}
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
sections[indexPath.section].collectionView?(collectionView, didEndDisplaying: cell, forItemAt: indexPath)
}
}
// MARK: - UICollectionViewDataSource
extension NewTabPageViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
sections.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
sections[section].collectionView(collectionView, numberOfItemsInSection: section)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
sections[indexPath.section].collectionView(collectionView, cellForItemAt: indexPath)
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
sections[indexPath.section].collectionView?(collectionView, viewForSupplementaryElementOfKind: kind, at: indexPath) ?? UICollectionReusableView()
}
func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
sections[indexPath.section].collectionView?(collectionView, contextMenuConfigurationForItemAt: indexPath, point: point)
}
func collectionView(_ collectionView: UICollectionView, previewForHighlightingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? {
guard let indexPath = configuration.identifier as? IndexPath else {
return nil
}
return sections[indexPath.section].collectionView?(collectionView, previewForHighlightingContextMenuWithConfiguration: configuration)
}
func collectionView(_ collectionView: UICollectionView, previewForDismissingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? {
guard let indexPath = configuration.identifier as? IndexPath else {
return nil
}
return sections[indexPath.section].collectionView?(collectionView, previewForHighlightingContextMenuWithConfiguration: configuration)
}
func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
guard let indexPath = configuration.identifier as? IndexPath else {
return
}
sections[indexPath.section].collectionView?(collectionView, willPerformPreviewActionForMenuWith: configuration, animator: animator)
}
}
// MARK: - UICollectionViewDragDelegate & UICollectionViewDropDelegate
extension NewTabPageViewController: UICollectionViewDragDelegate, UICollectionViewDropDelegate {
func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
// Check If the item that is dragged is a favourite item
guard sections[indexPath.section] is FavoritesSectionProvider else {
return []
}
let itemProvider = NSItemProvider(object: "\(indexPath)" as NSString)
let dragItem = UIDragItem(itemProvider: itemProvider).then {
$0.previewProvider = { () -> UIDragPreview? in
guard let cell = collectionView.cellForItem(at: indexPath) as? FavoriteCell else {
return nil
}
return UIDragPreview(view: cell.imageView)
}
}
return [dragItem]
}
func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {
guard let sourceIndexPath = coordinator.items.first?.sourceIndexPath else { return }
let destinationIndexPath: IndexPath
if let indexPath = coordinator.destinationIndexPath {